package com.web.cms.doc.provider;

import com.blue.jdbc.Page;
import com.blue.validation.ValidationUtil;
import com.blue.validation.group.SaveModel;
import com.blue.validation.group.UpdateModel;
import com.web.cms.doc.cache.WebCache;
import com.web.cms.doc.exception.WebException;
import com.web.cms.doc.facade.WebFacade;
import com.web.cms.doc.message.WebRequest;
import com.web.cms.doc.message.WebResponse;
import com.web.cms.doc.model.Web;
import com.web.cms.doc.service.WebService;
import com.web.cms.doc.util.WebConvertor;
import com.web.core.async.redis.CacheRefreshSender;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Component("cmsWebProvider")
public class WebProvider implements WebFacade
{
	@Autowired
	private WebService webService;
	@Autowired
	private WebCache webCache;
	@Resource
	private CacheRefreshSender cacheRefreshSender;
	
	public WebProvider()
	{
	}

	@Override
	public WebResponse add(WebRequest request)
	{
		ValidationUtil.valid(request, SaveModel.class);
		Web web = WebConvertor.toWeb(request);
		web = webService.save(web);
		cacheRefreshSender.send(CacheRefreshSender.DOC_WEB_CACHE, web.getId());
		WebResponse response = WebConvertor.toResponse(web);
		return response;
	}

	@Override
	public WebResponse update(WebRequest request)
	{
		ValidationUtil.valid(request, UpdateModel.class);
		Web web = WebConvertor.toWeb(request);
		web = webService.save(web);
		cacheRefreshSender.send(CacheRefreshSender.DOC_WEB_CACHE, web.getId());
		WebResponse response = WebConvertor.toResponse(web);
		return response;
	}

	@Override
	public WebResponse get(Integer id)
	{
		if (id == null)
			throw new WebException("网站ID不能为空");
		
		Web web = webCache.get(id);
		WebResponse response = WebConvertor.toResponse(web);
		return response;
	}

	@Override
	public Page<WebResponse> listPage(WebRequest request, int start, int size)
	{
		Web web = WebConvertor.toWeb(request);
		Page<Web> page = new Page<>(size);
		page.setCurPage(start);
		page = webService.list(web, page);
		Page<WebResponse> resonsePage = WebConvertor.toResponse(page);
		return resonsePage;
	}
	
	@Override
	public List<WebResponse> listAll()
	{
		List<Web> list = webCache.list();
		List<WebResponse> responseList = WebConvertor.toResponse(list);
		return responseList;
	}

	@Override
	public WebResponse getByCode(String code)
	{
		if (code == null || code.isEmpty())
			throw new WebException("网站代码不能为空");
		
		Web web = webCache.getByCode(code);
		WebResponse response = WebConvertor.toResponse(web);
		return response;
	}
	
	@Override
	public void refresh()
	{
		cacheRefreshSender.send(CacheRefreshSender.DOC_WEB_CACHE);
	}
	
}
